package com.pro.framework.api;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PolynomialEquationSolver {

    // 解析多项式方程并返回系数的映射（幂次 -> 系数）
    public static Map<Integer, Double> parsePolynomialEquation(String equation) {
        // 移除所有空白字符
        equation = equation.replaceAll("\\s+", "");

        // 正则表达式匹配多项式项（如 2x^2, -3x, 5）
        Pattern termPattern = Pattern.compile("([+-]?\\d*\\.?\\d*)x?\\^?(\\d*)");
        Matcher termMatcher = termPattern.matcher(equation);

        Map<Integer, Double> coefficients = new HashMap<>();
        while (termMatcher.find()) {
            // 提取系数
            String coeffStr = termMatcher.group(1);
            double coefficient = coeffStr.isEmpty() || coeffStr.equals("+") ? 1 :
                    coeffStr.equals("-") ? -1 : Double.parseDouble(coeffStr);

            // 提取幂次
            String powerStr = termMatcher.group(2);
            int power = powerStr.isEmpty() ? (termMatcher.group(0).contains("x") ? 1 : 0) : Integer.parseInt(powerStr);

            // 将系数存入映射
            coefficients.put(power, coefficients.getOrDefault(power, 0.0) + coefficient);
        }

        return coefficients;
    }

    // 求解一元二次方程 ax^2 + bx + c = 0
    public static double[] solveQuadraticEquation(Map<Integer, Double> coefficients) {
        double a = coefficients.getOrDefault(2, 0.0);
        double b = coefficients.getOrDefault(1, 0.0);
        double c = coefficients.getOrDefault(0, 0.0);

        double discriminant = b * b - 4 * a * c;
        if (discriminant < 0) {
            throw new IllegalArgumentException("方程无实数解");
        }

        double sqrtDiscriminant = Math.sqrt(discriminant);
        double x1 = (-b + sqrtDiscriminant) / (2 * a);
        double x2 = (-b - sqrtDiscriminant) / (2 * a);

        return new double[]{x1, x2};
    }

    public static void main(String[] args) {
        String equation = "2x^2 + 3x - 5 = 0"; // 自定义方程
        System.out.println("方程: " + equation);

        try {
            // 解析方程
            Map<Integer, Double> coefficients = parsePolynomialEquation(equation);
            System.out.println("系数: " + coefficients);

            // 求解方程
            double[] solutions = solveQuadraticEquation(coefficients);
            System.out.println("解: x1 = " + solutions[0] + ", x2 = " + solutions[1]);
        } catch (IllegalArgumentException e) {
            System.out.println("错误: " + e.getMessage());
        }
    }
}